package com.demo.spring_demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")

    @Bean
    public DruidDataSource getDruidDataSource() {
        return new DruidDataSource();
    }


    //后台监控:web.xml
    //springboot内置了servlet
    @Bean
    public ServletRegistrationBean druidServlet() {

        ServletRegistrationBean<StatViewServlet> statViewServlet = new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(), "/druid/*");
        //后台需要有人登录
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("loginUsername", "admin");   //键值key是固定的
        initParameters.put("loginPassword", "123456");

        //允许谁访问allow 值为空 允许所有人访问
        //initParameters.put("allow", "");

        //禁止谁访问
//        initParameters.put("主机名", "IP地址");

        statViewServlet.setInitParameters(initParameters);
        return statViewServlet;
    }

    //添加过滤filter
    @Bean
    public FilterRegistrationBean druidFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //过滤那些请求
        Map<String, String> initParameter = new HashMap<>();
        //过滤掉这些请求
        initParameter.put("exclusions", "*.js,*.css,*.ico,/druid/*");
        bean.setInitParameters(initParameter);
        return bean;
    }


}
